<?php
namespace mdm\admin\models\form;

use Yii;
use mdm\admin\models\User;
use yii\base\Model;

/**
 * Signup form
 */
class Signup extends Model
{
    public $username;
    public $email;
    public $password;
    public $realname;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username', 'filter', 'filter' => 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => 'mdm\admin\models\User', 'message' => '此账号已经存在'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['realname', 'filter', 'filter' => 'trim'],
            ['realname', 'required', 'message' => '真实姓名必须为2-5个汉字'],
            ['realname', 'match', 'pattern' => '/^[\x{4e00}-\x{9fa5}]{2,5}$/u', 'message' => '真实姓名必须为2-5个汉字'],
            ['realname', 'string', 'min' => 2, 'max' => 255],

            ['email', 'filter', 'filter' => 'trim'],
            ['email', 'required', 'message' => '邮箱地址不能为空'],
            ['email', 'unique', 'targetClass' => 'mdm\admin\models\User', 'message' => '此邮箱地址已经存在'],
            ['email', 'match', 'pattern' => '/@xiaoxiongyouxi\.com$/', 'message' => '必须为小熊游戏公司企业邮箱'],

            ['password', 'required'],
            ['password', 'string', 'min' => 6],
            ['password', 'checkFormat'],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if ($this->validate()) {
            $user = new User();
            $user->username = $this->username;
            $user->realname = $this->realname;
            $user->email = $this->email;
            $user->setPassword($this->password);
            $user->generateAuthKey();
            if ($user->save()) {
                return $user;
            }
        }

        return null;
    }

    public function checkFormat(){
        $patternCapital = '/[A-Z]/';
        $patternLower = '/[a-z]/';
        $patternNumber = '/[0-9]/';

        if( !(preg_match($patternCapital, $this->password)
            && preg_match($patternLower, $this->password)
            && preg_match($patternNumber, $this->password)
            )
        ){
            $this->addError('password', '密码必须包含数字、大小写字母');
        }
    }
}
